/**
 * Created by Administrator on 2015/4/2.
 */
var JqSelector = (function(){
	//基类
	var Selector = PFT_GLOBAL.U.RichBase.extend({
		api : "/new/d/call/jh_prod_f.php",
		template : {
			loading : '<li class="">正在加载数据...</li>',
			timeout : '<li class="">请求超时</li>',
			fail : '<li class="">请求失败</li>',
			serverError : '<li class="">服务器出错</li>',
			empty : '<li class="">尚无景点</li>',
			listItem : '<li class="item" data-id="<%=id%>"><%=scenic_name%></li></li>'
		},
		init : function(opt){
			this.loadList();
		},
		EVENTS : {
			"click" : {
				"li.item" : function(self,e){
					self.onItemClick(self,e);
				}
			}
		},
		loadList : function(keyword){
			var self = this;
			var listUl = this.get("listUl");
			var template = this.template;
			var selectid = this.get("selectid");
			this.query(keyword,{
				loading : function(){listUl.html(template.loading)},
				removeLoading : function(){listUl.html("")},
				timeout : function(){listUl.html(template.timeout)},
				error : function(){listUl.html(template.error)},
				serverError : function(){listUl.html(template.serverError)},
				empty : function(){listUl.html(template.empty)},
				success : function(res){
					var list = res.list;
					var html = "";
					for(var i in list){
						html += self.parseTemplate(template.listItem,list[i]);
					}
					self.updateList(html);
				}
			});
		},
		onItemClick : function(self,e){
			var curItem = $(e.currentTarget);
			curItem.toggleClass("active");
			self.fire("onItemClick",self,e);
		},
		updateList : function(html){
			var listUl = this.get("listUl");
			listUl.html(html);
			this.fire("listUl.update",listUl);
		},
		query : function(keyword,config){
			keyword = keyword || "";
			config = config || {};
			var api = this.api;
			var fn = new Function();
			var loading = config.loading || fn;
			var removeLoading = config.removeLoading || fn;
			var timeout = config.timeout || fn;
			var serverError = config.serverError || fn;
			var success = config.success || fn;
			var empty = config.empty || fn;
			var fail = config.fail || fn;
			PFT_GLOBAL.G.Ajax({
				url : api,
				type : "GET",
				dataType : "JSON",
				data : {
					action : "search",
					k : keyword
				},
				loading : function(){loading()},
				removeLoading : function(){removeLoading()},
				timeout : function(){timeout()},
				serverError : function(){serverError()}
			},function(res){
				if(res && res.state=="ok" && res.list){
					if(res.list.length){
						success(res);
					}else{
						empty(res);
					}
				}else{
					fail(res);
				}
			})
		},
		/**
		 * 从列表中减去(只是隐藏 没有真正删除)一项或多项item
		 */
		minu : function(){
			var listUl = this.get("listUl");
			listUl.children(".active").removeClass("active").addClass("hide");
		},
		/**
		 * 把一项或多项加入列表中
		 * @param selectid 数组
		 */
		add : function(selectid){
			var listUl = this.get("listUl");
			for(var i in selectid){
				listUl.children("[data-id="+selectid[i]+"]").removeClass("hide");
			}
		}
	});

	//景点库类
	var Jingquku = Selector.extend({
		EVENTS : {
			"click" : {
				"li.item" : function(self,e){
					self.onItemClick(self,e);
				}
			},
			"input propertychange" : {
				"input.searchBar" : function(self,e){
					self.onInputChange(self,e);
				}
			},
			"focus" : {
				"input.searchBar" : function(self,e){

				}
			},
			"blur" : {
				"input.searchBar" : function(self,e){

				}
			}
		},
		onInputChange : function(self,e){
			self.fire("onInputChange",self,e);
			var inp = $(e.target);
			var val = inp.val();
			this.loadList(val);
		}
	});

	//已选择景点
	var JingquSelected = Selector.extend({
		template : {
			loading : '<li class="">正在加载数据...</li>',
			timeout : '<li class="">请求超时</li>',
			fail : '<li class="">请求失败</li>',
			serverError : '<li class="">服务器出错</li>',
			empty : '<li class="">尚无景点</li>',
			listItem : '<li class="item hide" data-id="<%=id%>"><%=scenic_name%></li></li>'
		},
		onInputChange : function(self,e){}
	});

	//包装类
	var JingquPop = PFT_GLOBAL.U.RichBase.extend({
		api : "/new/d/call/jh_prod_f.php",
		hasInit : false,
		EVENTS : {
			"click" : {
				"#selectorBtnGroup .add" : function(self,e){
					self.onAddBtnClick(e);
				},
				"#selectorBtnGroup .minu" : function(self,e){
					self.onMinuBtnClick(e);
				},
				"#jingquSaveBtn" : function(self,e){
					self.onSaveBtnClick(self,e);
				},
				".addBtn" : function(self,e){
					self.onCreateBtnClick(self,e);
				}
			}
		},
		init : function(){
			var s = this.get("s");
			var ss = this.get("ss");
			var slistUl = s.get("listUl");
			var sslistUl = ss.get("listUl");
			var btnGroup = this.get("btnGroup");
			var topBtn = btnGroup.find(".add");
			var botBtn = btnGroup.find(".minu");
			ss.on("listUl.update",function(){
				var data = ss.get("selectData").data;
				for(var i in data){
					var id = data[i]["id"];
					sslistUl.children("[data-id="+id+"]").removeClass("hide");
				}
			});
			ss.on("onItemClick",function(self,e){
				if(sslistUl.children(".active").length){
					botBtn.addClass("active")
				}else{
					botBtn.removeClass("active")
				}
			})
			s.on("listUl.update",function(){
				sslistUl.children().not(".hide").each(function(){
					var item = $(this);
					var id = item.attr("data-id");
					if(id) slistUl.children("[data-id="+id+"]").addClass("hide");
				})
			})
			s.on("onItemClick",function(self,e){
				if(slistUl.children(".active").length){
					topBtn.addClass("active")
				}else{
					topBtn.removeClass("active")
				}
			})
		},
		onAddBtnClick : function(e){
			var s = this.get("s");
			var ss = this.get("ss");
			var ids = [];
			var targetBtn = this.get("btnGroup").find(".add");
			if(!targetBtn.hasClass("active")) return false;
			s.get("listUl").children(".active").each(function(){
				ids.push($(this).attr("data-id"))
			})
			s.minu();
			ss.add(ids);
			targetBtn.removeClass("active");
			if(ss.get("listUl").children().not(".hide").size()){
				$("#jingquSaveBtn").removeClass("disabled");
			}else{
				$("#jingquSaveBtn").addClass("disabled");
			}
		},
		onMinuBtnClick : function(e){
			var s = this.get("s");
			var ss = this.get("ss");
			var ids = [];
			var targetBtn = this.get("btnGroup").find(".minu");
			if(!targetBtn.hasClass("active")) return false;
			ss.get("listUl").children(".active").each(function(){
				ids.push($(this).attr("data-id"))
			})
			ss.minu();
			s.add(ids);
			targetBtn.removeClass("active");
			//if(ss.get("listUl").children().not(".hide").size()){
			//	$("#jingquSaveBtn").removeClass("disabled");
			//}else{
			//	$("#jingquSaveBtn").addClass("disabled");
			//}
		},
		onCreateBtnClick : function(self,e){
			var lid = $("#lid").val();
			var parentId = this.get("container").find(".title").data("id");
			console.log("lid="+lid+" parentId="+parentId);
			window.location.href = 'prod_edits_child.html?lid='+lid+'&id='+parentId+'&parentId='+parentId;
		},
		open : function(opt){
			opt = opt || {};
			var title = opt.title || "";
			var id = opt.id || "";
			var dialog = this.get("dialog");
			var s = this.get("s");
			var ss = this.get("ss");
			this.get("container").find(".title").text(opt.title).data("id",id);
			ss.set("selectData",opt);
			dialog.open();
		},
		//提交保存已选择的子景点
		onSaveBtnClick : function(self,e){
			var saveBtn = $(e.currentTarget);
			if(saveBtn.hasClass("disabled")) return false;
			var api = this.api;
			var parentId = this.get("container").find(".title").data("id");
			var childrenId = this.get("ss").get("listUl").children().not(".hide").map(function(){
				return $(this).attr("data-id");
			});
			childrenId = Array.prototype.join.call(childrenId,",");
			if(!parentId){
				console && console.log("缺省parentId");
				return false;
			}
			PFT_GLOBAL.G.Ajax({
				url : api,
				type : "POST",
				dataType : "JSON",
				data : {
					action : "setChild",
					parentId : parentId,
					childrenId : childrenId
				},
				loading : function(){
					saveBtn.addClass("loading").find(".t").text("正在保存...")
				},
				removeLoading : function(){
					saveBtn.removeClass("loading").find(".t").text("保存")
				}
			},function(res){
				if(res.status=="success"){
					PFT_GLOBAL.U.Alert("success",'<p style="width:200px;">保存成功</p>')
				}else{
					res.msg = res.msg || "保存失败，请稍后重试";
					PFT_GLOBAL.U.Alert("success",'<p style="width:200px;">'+res.msg+'</p>')
				}
			})
		}
	})


	function setUp(){
		var jingquSelected = new JingquSelected({
			container : $("#jingquSelectedContainer"),
			listUl : $("#jingqukuSelectedListUl")
		});
		var jingquku = new Jingquku({
			container : $("#jingquContainer"),
			listUl : $("#jingqukuListUl"),
			searchInp : $("#jingquSearchInp")
		});
		var dialog = new PFT_GLOBAL.U.Dialog({
			maskId : "#mask",
			containerId : "#jingquSelectDialog",
			closeBtnId : "#jingquSelectCloseBtn"
		});
		var pop = new JingquPop({
			container : $("#jingquSelectDialog"),
			s : jingquku,
			ss : jingquSelected,
			btnGroup : $("#selectorBtnGroup"),
			dialog : dialog
		});
		return pop;
	}

	return{
		setUp : setUp
	}

})();

function onCreateNewSubjqBtnClick(e){
	var btn = $(e.target);
	var opt = {};
	opt["id"] = btn.parent().data("id");
	opt["title"] = btn.parent().find(".jqname").text();
	opt["data"] = [];
	var selector = $("body").data("selector");
	btn.prev().children().each(function(){
		var item = $(this);
		var json = {};
		json["id"] = item.attr("data-id");
		json["title"] = item.text();
		opt["data"].push(json);
	})
	if(!selector){
		selector = JqSelector.setUp();
		$("body").data("selector",selector);
	}
	selector.open(opt)
}

$("#childListUl").on("click",".createNewSubjqBtn",onCreateNewSubjqBtnClick)